<template>
    <div class="edu-page-warp">
        <div class="edu-page-title mg-top">
            {{$t('schoolCalendar.list')}}
        </div>
        <el-card shadow="never" body-style="padding: 24px;">
            <div class="edu-opertion-bar">
                <div class="float-left">
                  <el-form :model="queryParams" :inline="true" ref="queryParams" class="bg-white ">
                      <el-form-item :label="$t('schoolCalendar.schoolYear')">
                          <el-select v-model="queryParams.year">
                              <el-option v-for="item in options.years"
                                  :key="item.id"
                                  :label="item.typeName"
                                  :value="item.id">
                              </el-option>
                          </el-select>
                      </el-form-item>
                      <el-form-item class="float-right">
                          <el-button @click="reset">{{$t('message.reset')}}</el-button>
                          <el-button type="primary" @click="getCalendarList">{{$t('message.filter')}}</el-button>   
                      </el-form-item>
                    </el-form>
                </div>
                <div class="float-right">
                    <el-button @click="addCalendar" type="primary">{{$t('message.add')}}</el-button>
                    <el-button @click="deleteCalendar(null)" type="danger">{{$t('message.delete')}}</el-button>
                </div> 
            </div>
            <el-table :data="workflows.list" size="mini" @selection-change="handleSelectionChange" stripe>
                <el-table-column type="selection" width="30"></el-table-column>
                <el-table-column type="index" width="55" :label="$t('message.order')" align="center"></el-table-column>
                <!-- <el-table-column :label="$t('schoolCalendar._')">
                    <template slot-scope="scope">{{getYearLable(scope.row)+getTermLable(scope.row)}}</template>
                </el-table-column> -->
                <el-table-column :label="$t('schoolCalendar.schoolYear')">
                    <template slot-scope="scope">{{scope.row.perYear}}</template>
                </el-table-column>
                <el-table-column :label="$t('schoolCalendar.schoolTerm')">
                    <template slot-scope="scope">{{getTermLable(scope.row)}}</template>
                </el-table-column>
                <el-table-column :label="$t('message.startDate')">
                    <template slot-scope="scope">{{formatDate(scope.row.beginDay)}}</template>
                </el-table-column>
                <el-table-column :label="$t('message.endDate')">
                    <template slot-scope="scope">{{formatDate(scope.row.endDay)}}</template>
                </el-table-column>
                <el-table-column :label="$t('schoolCalendar.weekNum')">
                    <template slot-scope="scope">{{scope.row.weekNum}}</template>
                </el-table-column>
                <el-table-column :label="$t('schoolCalendar.firstDayOfWeek')">
                    <template slot-scope="scope">
                      <span v-if="scope.row.weekBenginDay==1">{{$t('message.sunday')}}</span>
                      <span v-if="scope.row.weekBenginDay==2">{{$t('message.monday')}}</span>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('message.operating')">
                    <template slot-scope="scope">
                        <el-button type="text" @click="editlCalendar(scope.row)" size="mini">{{$t('message.edit')}}</el-button>
                        <el-button type="text" @click="deleteCalendar([scope.row.id])" size="mini" >{{$t('message.delete')}}</el-button>
                        <el-button type="text" @click="exportCalendar(scope.row)" size="mini" >{{$t('message.export')}}</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="edu-pagination">
                <div class="float-right">
                    <el-pagination
                        @size-change="onPageSizeChange"
                        @current-change="onCurrentPageChange"
                        :current-page="queryParams.pageNum_"
                        :page-sizes="[20,50,100,500,1000]"
                        :page-size="queryParams.pageSize_"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="workflows.total_" style="float: right;margin:10px 60px 0 0;">
                    </el-pagination>
                </div>
            </div>
        </el-card>
        <el-dialog :title="dialogTitle" width="42%" :visible.sync="showEditDialog" @close="resetAddForm">
          <el-form :model="createForm" ref="createForm" label-width="100px" :rules="rules" class="createForm">
              <el-form-item :label="$t('schoolCalendar.schoolYear')" prop="year" required>
                  <el-select v-model="createForm.year" style="width:100%;" @change="yearChange">
                      <el-option v-for="item in options.years"
                          :key="item.id"
                          :label="item.typeName"
                          :value="item.id">
                      </el-option>
                  </el-select>
              </el-form-item>
              <el-form-item :label="$t('schoolCalendar.schoolTerm')" prop="term" required>
                <el-select v-model="createForm.term">
                    <el-option v-for="item in options.terms"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                </el-select>
              </el-form-item>
              <el-form-item :label="$t('message.time')" required>
                <el-col :span="11">
                  <el-form-item prop="beginDay" style="width:100%;" required>
                    <el-date-picker type="date" :placeholder="$t('message.startDate')" 
                      value-format="timestamp" size="mini"
                      v-model="createForm.beginDay" 
                      :default-value="datePickerDefault"></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col class="line" :span="2">-</el-col>
                <el-col :span="11">
                  <el-form-item prop="endDay" style="width:100%;" required>
                    <el-date-picker type="date" :placeholder="$t('message.endDate')" 
                      value-format="timestamp"
                      v-model="createForm.endDay" 
                      :default-value="datePickerDefault"></el-date-picker>
                  </el-form-item>
                </el-col>
              </el-form-item>
              <el-form-item :label="$t('schoolCalendar.firstDayOfWeek')" required>
                <el-radio-group v-model="createForm.weekBenginDay">
                  <el-radio label="1" ><span v-t="'message.sunday'"></span></el-radio>
                  <el-radio label="2" ><span v-t="'message.monday'"></span></el-radio>
                </el-radio-group>
              </el-form-item>
          </el-form> 
          <span slot="footer" class="dialog-footer">
            <el-button @click="showEditDialog = false">{{$t('message.cancel')}}</el-button>
            <el-button type="primary" @click="submitForm">{{$t('message.submit')}}</el-button>
          </span>
        </el-dialog>
    </div>
</template>
<script>
/**
 * 校历管理
 */
import SchoolCalendarApi from "common/src/api/calendars";
import { queryDic } from "common/src/api/dictionary";
import UTILS from "common/src/utils/utils";

export default {
  name: "SchoolCalendar",
  data() {
    return {
      isEdit: false,
      showEditDialog: false,
      options: {
        years: [{ typeName: this.$t("message.all"), id: "" }],
        terms: [{ label: this.$t("message.plsSelect"), value: "" }]
      },
      queryParams: {
        year: "",
        pageNum_: 1,
        pageSize_: 20
      },
      workflows: [],
      selectionDatas: [],
      createForm: {
        year: "",
        yearTo: "",
        term: "",
        beginDay: "",
        endDay: "",
        weekBenginDay: "1"
      },
      datePickerDefault: new Date(),
      rules: {
        year: [
          {
            required: true,
            message: this.$t("message.inputRequired"),
            trigger: "change"
          }
        ],
        yearTo: [
          {
            required: true,
            message: this.$t("message.inputRequired"),
            trigger: "change"
          }
        ],
        term: [
          {
            required: true,
            message: this.$t("message.inputRequired"),
            trigger: "change"
          }
        ],
        beginDay: [
          {
            required: true,
            message: this.$t("message.inputRequired"),
            trigger: "change"
          }
        ],
        endDay: [
          {
            required: true,
            message: this.$t("message.inputRequired"),
            trigger: "change"
          }
        ],
        weekBenginDay: [
          {
            required: true,
            message: this.$t("message.inputRequired"),
            trigger: "change"
          }
        ]
      }
    };
  },
  created() {
    let currnetYear = new Date().getFullYear() + 5;
    for (let index = 5; index > 0; index--) {
      let year = currnetYear - index;
      this.options.years.push({ typeName: year, id: year });
    }
  },
  mounted() {
    this.getOptions();
  },
  activated() {
  },
  methods: {
    getOptions() {
      let data = {
          lang: this.$store.getters.language || "cn",
          type: "allChild",
          keys: ["X_XLXQ"]
        };
        queryDic(data).then(res => {
            if (res.code == 200) {
              let data = res.data['X_XLXQ'];
              for (let key in data) {
                this.options.terms.push({
                  value: key+'',
                  label: data[key]
                });
              }
            }
            this.getCalendarList();
        });
    },
    getYearLable(data) {
      return data.year + '-' + (data.year+1);
    },
    getTermLable(data) {
      let text = data.term;
      for (const term of this.options.terms) {
        if(data.term == term.value){
          text = term.label;
        }
      }
      return text;
    },
    formatDate(timenumber) {
      return moment(timenumber).format('YYYY-MM-DD');
    },
    handleSelectionChange(val) {
      this.selectionDatas = val;
    },
    yearChange(val) {
      this.createForm.beginDay = null;
      this.createForm.endDay = null;
      this.datePickerDefault = moment(val, 'YYYY').toDate();
    },
    deleteCalendar(ids) {
      if (ids == null) {
        ids = [];
        for (const data of this.selectionDatas) {
          ids.push(data.id);
        }
      }
      if (ids.length < 1) {
        this.$alert(
          this.$t("common.pla.plsSelectRecord"),
          this.$t("message.prompt"),
          { type: "warning" }
        );
        return;
      }
      this.$confirm(this.$t('schoolCalendar.deleteConfirm'), this.$t('message.confirm'), {
        distinguishCancelAndClose: false,
        confirmButtonText: this.$t('message.confirm'),
        cancelButtonText: this.$t('message.cancel')
      }).then(()=>{
        SchoolCalendarApi.deleteCalendar(ids).then(response => {
          if (response.code == 200) {
            this.$message({
              type: "success",
              message: this.$t("message.deleteSuccess")
            });
  
            this.getCalendarList();
          } else {
            this.$message({
              type: "info",
              message: response.msg
            });
          }
        });
      });
    },
    exportCalendar(data) {
      if (data == null) {
        this.$alert(
          this.$t("common.pla.plsSelectRecord"),
          this.$t("message.prompt"),
          { type: "warning" }
        );
        return;
      }
      let name = this.getYearLable(data) + this.getTermLable(data);
      SchoolCalendarApi.exportFile(data.id, name);
    },
    getCalendarList() {
      SchoolCalendarApi.searchCalendarList(this.queryParams).then(response => {
        if (response.code === 200) {
          this.workflows = response.data;
        } else {
          throw response.msg;
        }
      });
    },
    onPageSizeChange(size) {
      this.queryParams.pageSize_ = size;
      this.getCalendarList();
    },
    onCurrentPageChange(currentPage) {
      this.queryParams.pageNum_ = currentPage;
      this.getCalendarList();
    },
    reset() {
      this.queryParams.year = "";
      this.queryParams.pageNum_ = 1;
      this.queryParams.pageSize_ = 20;
      this.getCalendarList();
    },
    editlCalendar(data) {
      SchoolCalendarApi.get(data.id).then(rsp => {
        this.createForm = rsp.data;
        this.createForm.term += '';
        this.createForm.weekBenginDay += '';
        this.isEdit = true;
        this.dialogTitle = this.$t('message.edit');
        this.showEditDialog = true;
      });
    },
    addCalendar() {
      for (const key in this.createForm) {
        this.createForm[key] = "";
      }
      this.createForm.weekBenginDay = '1';
      this.dialogTitle = this.$t('message.add');
      this.showEditDialog = true;
      this.isEdit = false;
    },
    resetAddForm() {
      this.$refs.createForm.resetFields();
    },
    submitForm() {
      this.$refs.createForm.validate(valid => {
        if (valid) {
          let _promise = null;
          let message = this.$t('message.addSuccess');
          if (this.isEdit) {
            message = this.$t('message.editSuccess');
            _promise = SchoolCalendarApi.update(this.createForm);
          } else {
            _promise = SchoolCalendarApi.add(this.createForm);
          }
          _promise.then(response => {
            if (response.code == 200) {
              this.$message({
                type: "success",
                message: message
              });
              this.showEditDialog = false;
              this.getCalendarList();
            } else {
              this.$message({
                type: "info",
                message: response.msg
              });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.createForm {
  .line {
    text-align: center;
  }
  .el-date-editor.el-input,
  .el-date-editor.el-input__inner {
    width: 100%;
  }
  .el-select {
    width: 100%;
  }
}
</style>
